package com.sky.Task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
@EnableScheduling
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 支付超时订单处理
     */
    @Scheduled(cron = "0 * * * * ?")    //每分钟执行一次
    public void processTimeoutOrder() {
        log.info("开始进行支付超时订单处理：{}", LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);  //在该时间前未支付的订单都已超时
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);

        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED); //已取消
                orders.setCancelReason(MessageConstant.PAYMENT_TIMEOUT_AUTO_CANCEL);    //取消原因
                orders.setCancelTime(LocalDateTime.now());  //取消时间

                //更新订单
                orderMapper.update(orders);
            });
        }
    }

    /**
     * 派送中状态的订单处理
     */
    @Scheduled(cron = "0 0 1 * * ?")   //每天凌晨1点执行一次
    public void processDeliveryOrder() {
        log.info("开始进行未完成订单状态处理：{}", LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);  //处理前一天所有派送中状态的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);

        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED); //已完成

                //更新订单
                orderMapper.update(orders);
            });
        }
    }


}
